package com.sadam.ui4.FragmentSelfPage;

// 导入所需类
import com.sadam.ui4.Data.MySqLiteOpenHelper;
import com.sadam.ui4.FragmentSelfPage.FragmentComposition.FragmentComposition;
import com.sadam.ui4.FragmentSelfPage.FragmentComposition.FragmentLikedVideos;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.tabs.TabLayout;

import com.sadam.ui4.ActivityLogin;
import com.sadam.ui4.Data.User;

import com.sadam.ui4.MainActivity;
import com.sadam.ui4.Utils.ValidationUtils;
import com.sadam.ui4.R;

import android.widget.EditText;
import android.widget.Toast;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FragmentSelfPage#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragmentSelfPage extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private static final int REQUEST_PICK_IMAGE = 1000;
    private static final int REQUEST_PERMISSION_READ_STORAGE = 100;

    private String mParam1;
    private String mParam2;

    private FragmentComposition fragmentComposition;
    private FragmentLikedVideos fragmentLikedVideos;

    private OnFragmentInteractionListener mListener;

    private TabLayout tabLayout_note_like_product;
    private TextView textViewSignatureContent;

    private Fragment currentFragment;

    private ImageButton imageButtonAvatar;
    private TextView textViewUsername; // 用户名显示控件
    private TextView textViewUserId;   // ID 显示控件（可选，也建议统一声明）

    // 添加 Fragment 状态管理变量
    private boolean isCompositionLoaded = false;
    private boolean isLikedLoaded = false;
    private int currentTabPosition = 0;

    // 添加刷新控制
    private boolean isRefreshing = false;
    private long lastRefreshTime = 0;
    // 首页基本资料刷新
    private SwipeRefreshLayout swipeRefreshLayout;

    private boolean isRefreshingUserInfo = false;

    private MySqLiteOpenHelper dbHelper;

    private static final long MIN_USERINFO_REFRESH_INTERVAL = 1000; // 1秒内不允许重复刷新
    //作品和赞过栏刷新
    private static final long MIN_REFRESH_INTERVAL = 2000; // 2秒内不允许重复刷新

    // 添加获赞数显示控件
    private TextView textViewLikesCount;

    public FragmentSelfPage() {
        // Required empty public constructor
    }

    public static FragmentSelfPage newInstance(String param1, String param2) {
        FragmentSelfPage fragment = new FragmentSelfPage();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("FragmentSelfPage", "onResume: 刷新用户数据");
        if (!isCompositionLoaded && !isLikedLoaded) {
            refreshUserInfo();
        }
        // ✅ 优化：只在需要时加载当前Tab的数据
        if (currentTabPosition == 0 && !isCompositionLoaded) {
            loadCurrentTabData();
        } else if (currentTabPosition == 1 && !isLikedLoaded) {
            loadCurrentTabData();
        }
    }

    /**
     * 刷新当前显示的Fragment数据
     */
    private void refreshCurrentFragmentData() {
        Log.d("SwipeRefresh", "刷新当前Fragment数据，位置: " + currentTabPosition);

        switch (currentTabPosition) {
            case 0: // 作品页
                if (fragmentComposition != null) {
                    fragmentComposition.loadUserVideos();
                    Log.d("SwipeRefresh", "刷新作品列表");
                }
                break;
            case 1: // 赞过页
                if (fragmentLikedVideos != null) {
                    // 使用新的刷新方法
                    fragmentLikedVideos.refreshLikedVideos();
                    Log.d("SwipeRefresh", "刷新赞过列表");
                }
                break;
        }
    }


    /**
     * 刷新用户信息（优化版）
     */
    private void refreshUserInfo() {
        Log.d("SwipeRefresh", "刷新用户基本信息");

        User currentUser = ActivityLogin.getCurrentUserFromSharedPrefrences(
                requireContext(),
                ((MainActivity) requireActivity()).getMySqLiteOpenHelper()
        );

        if (currentUser != null) {
            // 设置用户信息到 UI
            textViewUsername.setText(currentUser.getName());
            textViewUserId.setText("ID：" + String.valueOf(currentUser.getId()));
            displayUserAvatar(requireContext(), currentUser);
            textViewSignatureContent.setText(currentUser.getSelfIntroduction());

            // 刷新用户作品总获赞数
            refreshUserLikesCount(currentUser.getId());

            Log.d("SwipeRefresh", "用户基本信息刷新完成");
        } else {
            // 用户未登录状态
            textViewUsername.setText("未登录");
            textViewUserId.setText("ID：--");
            textViewSignatureContent.setText("用户未登录");
            textViewLikesCount.setText("0");
            imageButtonAvatar.setImageResource(R.drawable.user_avatar);
            Log.d("SwipeRefresh", "用户未登录，显示默认信息");
        }
    }

    /**
     * 刷新用户作品总获赞数
     */
    /**
     * 刷新用户作品总获赞数（优化版）
     */
    public void refreshUserLikesCount(long userId) {
        Log.d("SwipeRefresh", "刷新用户获赞数，用户ID: " + userId);

        new Thread(() -> {
            try {
                // 从数据库获取用户作品总获赞数
                int totalLikes = ((MainActivity) requireActivity())
                        .getMySqLiteOpenHelper()
                        .getTotalLikesForUserVideos(userId);

                // 在主线程更新UI
                requireActivity().runOnUiThread(() -> {
                    if (textViewLikesCount != null) {
                        textViewLikesCount.setText(String.valueOf(totalLikes));
                        Log.d("SwipeRefresh", "用户获赞数更新: " + totalLikes);
                    }
                });
            } catch (Exception e) {
                Log.e("SwipeRefresh", "获取用户获赞数失败", e);
                requireActivity().runOnUiThread(() -> {
                    if (textViewLikesCount != null) {
                        textViewLikesCount.setText("0");
                    }
                });
            }
        }).start();
    }
    /**
     * 公开的刷新方法，供外部调用
     */
    public void refreshUserInfoExternally() {
        if (!isRefreshingUserInfo) {
            refreshAllData();
        }
    }
    /**
     * 刷新作品列表
     */
    public void refreshCompositionFragment() {
        if (currentFragment instanceof FragmentComposition) {
            ((FragmentComposition) currentFragment).loadUserVideos();
            Log.d("FragmentSelfPage", "刷新作品列表");
        } else {
            Log.d("FragmentSelfPage", "当前不是作品页面，不需要刷新作品列表");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // 加载布局
        View view = inflater.inflate(R.layout.fragment_self_page, container, false);
        // 初始化下拉刷新控件
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        // 统一初始化 UI 控件
        textViewUsername = view.findViewById(R.id.textView23);
        textViewUserId = view.findViewById(R.id.textView24);
        textViewSignatureContent = view.findViewById(R.id.textView_signature_content);
        textViewLikesCount = view.findViewById(R.id.textView_likes_count); // 新增：初始化获赞数控件
        imageButtonAvatar = view.findViewById(R.id.imageButton);
        Button buttonEditProfile = view.findViewById(R.id.button26);
        tabLayout_note_like_product = view.findViewById(R.id.tablayout_note_product_like);

        // 设置下拉刷新监听器
        setupSwipeRefreshLayout();

        // 设置编辑资料按钮点击事件
        buttonEditProfile.setOnClickListener(v -> showEditProfileDialog());

        // 刷新用户信息
        refreshUserInfo();

        // 设置个人介绍点击事件
        textViewSignatureContent.setOnClickListener(v -> showEditIntroductionDialog());

        // ✅ 修复：创建 Fragment 实例
        fragmentComposition = new FragmentComposition();
        fragmentLikedVideos = new FragmentLikedVideos();

        // ✅ 修复：延迟加载数据，确保 Fragment 完全初始化
        view.post(() -> {
            setupTabLayoutAndFragments();
        });

        return view;
    }

    /**
     * 设置下拉刷新
     */
    private void setupSwipeRefreshLayout() {
        // 设置刷新时进度条的颜色
        swipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light
        );

        // 设置下拉刷新的监听器
        swipeRefreshLayout.setOnRefreshListener(() -> {
            if (isRefreshingUserInfo) {
                swipeRefreshLayout.setRefreshing(false);
                return;
            }

            Log.d("SwipeRefresh", "下拉刷新触发");
            refreshAllData();
        });

        // 设置进度条的背景颜色
        swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.backgroundColor);
    }

    /**
     * 刷新所有数据
     */
    private void refreshAllData() {
        if (isRefreshingUserInfo) {
            Log.d("SwipeRefresh", "正在刷新中，跳过重复刷新");
            if (swipeRefreshLayout.isRefreshing()) {
                swipeRefreshLayout.setRefreshing(false);
            }
            return;
        }

        isRefreshingUserInfo = true;
        Log.d("SwipeRefresh", "开始刷新所有数据");

        new Thread(() -> {
            try {
                // 模拟网络请求延迟
                Thread.sleep(800);

                requireActivity().runOnUiThread(() -> {
                    // 刷新用户基本信息
                    refreshUserInfo();

                    // 刷新当前显示的Fragment数据
                    refreshCurrentFragmentData();

                    // 完成后停止刷新动画
                    swipeRefreshLayout.setRefreshing(false);
                    isRefreshingUserInfo = false;

                    Toast.makeText(requireContext(), "刷新完成", Toast.LENGTH_SHORT).show();
                    Log.d("SwipeRefresh", "所有数据刷新完成");
                });

            } catch (Exception e) {
                Log.e("SwipeRefresh", "刷新数据失败", e);
                requireActivity().runOnUiThread(() -> {
                    swipeRefreshLayout.setRefreshing(false);
                    isRefreshingUserInfo = false;
                    Toast.makeText(requireContext(), "刷新失败", Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    private void setupTabLayoutAndFragments() {
        try {
            // ✅ 确保Fragment实例不为null
            if (fragmentComposition == null) {
                fragmentComposition = new FragmentComposition();
            }
            if (fragmentLikedVideos == null) {
                fragmentLikedVideos = new FragmentLikedVideos();
            }

            // ✅ 先设置TabLayout监听器，确保点击能立即响应
            setupTabLayoutListener();

            // ✅ 然后添加Fragment
            if (getChildFragmentManager().findFragmentByTag("composition") == null) {
                getChildFragmentManager().beginTransaction()
                        .add(R.id.fragment_layout_note_product_like, fragmentComposition, "composition")
                        .add(R.id.fragment_layout_note_product_like, fragmentLikedVideos, "liked")
                        .hide(fragmentLikedVideos)
                        .commit();

                currentFragment = fragmentComposition;
                currentTabPosition = 0;

                // ✅ 延迟加载初始数据
                loadInitialFragmentData();
            }

        } catch (Exception e) {
            Log.e("FragmentSelfPage", "Fragment初始化失败", e);
        }
    }
    /**
     * 加载初始Fragment数据
     */
    private void loadInitialFragmentData() {
        Log.d("FragmentSelfPage", "加载初始Fragment数据");

        // ✅ 延迟加载初始数据，确保Fragment完全初始化
        if (fragmentComposition != null) {
            new android.os.Handler().postDelayed(() -> {
                if (isAdded() && fragmentComposition.isAdded() && !isCompositionLoaded) {
                    fragmentComposition.loadUserVideos();
                    isCompositionLoaded = true;
                    Log.d("FragmentSelfPage", "初始作品数据加载完成");
                }
            }, 200);
        }
    }

    /**
     * 设置TabLayout监听器（优化版）
     */
    private void setupTabLayoutListener() {
        tabLayout_note_like_product.clearOnTabSelectedListeners();

        tabLayout_note_like_product.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                Log.d("TabSwitch", "Tab选中: 位置 " + position);

                // 如果已经是当前Tab，不重复处理
                if (position == currentTabPosition) {
                    Log.d("TabSwitch", "已是当前Tab，跳过切换");
                    return;
                }

                Fragment newFragment = null;
                String fragmentName = "";

                switch (position) {
                    case 0:
                        newFragment = fragmentComposition;
                        fragmentName = "作品Fragment";
                        break;
                    case 1:
                        newFragment = fragmentLikedVideos;
                        fragmentName = "赞过Fragment";
                        break;
                    default:
                        return;
                }

                if (newFragment == null) {
                    Log.e("TabSwitch", fragmentName + " 为null");
                    recoverPreviousTab();
                    return;
                }

                // 执行Fragment切换
                performFragmentSwitch(newFragment, position);

                // ✅ 优化：切换后检查是否需要加载数据
                checkAndLoadTabData(position);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // 可以在这里暂停视频播放等操作
                Log.d("TabSwitch", "Tab取消选中: 位置 " + tab.getPosition());
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                Log.d("TabSwitch", "Tab重新选中: 位置 " + position);

                // ✅ 新增：双击Tab触发手动刷新
                handleTabReselected(position);
            }
        });
    }

    /**
     * 执行Fragment切换
     */
    private void performFragmentSwitch(Fragment newFragment, int newPosition) {
        getChildFragmentManager().beginTransaction()
                .hide(currentFragment)
                .show(newFragment)
                .commit();

        currentFragment = newFragment;
        currentTabPosition = newPosition;

        // 第一次显示才加载
        if (newPosition == 1 && !isLikedLoaded && fragmentLikedVideos != null) {
            isLikedLoaded = true;
        }
    }
    /**
     * 处理Tab重新选中（双击刷新）
     */
    private void handleTabReselected(int position) {
        long currentTime = System.currentTimeMillis();

        // 防止频繁刷新
        if (currentTime - lastRefreshTime < MIN_REFRESH_INTERVAL) {
            Log.d("TabSwitch", "刷新过于频繁，跳过");
            return;
        }

        lastRefreshTime = currentTime;

        // 显示刷新提示
        Toast.makeText(requireContext(), "刷新中...", Toast.LENGTH_SHORT).show();

        // 根据当前Tab刷新对应数据
        switch (position) {
            case 0:
                refreshCompositionData();
                break;
            case 1:
                refreshLikedData();
                break;
        }
    }
    /**
     * 加载对应Tab的数据
     */
    private void loadFragmentData(int position) {
        Log.d("TabSwitch", "加载Tab数据: " + position);

        switch (position) {
            case 0: // 作品页
                if (!isCompositionLoaded && fragmentComposition != null) {
                    Log.d("TabSwitch", "首次加载作品数据");
                    fragmentComposition.loadUserVideos();
                    isCompositionLoaded = true;
                } else if (fragmentComposition != null) {
                    Log.d("TabSwitch", "作品数据已加载，可选择性刷新");
                }
                break;

            case 1: // 赞过页
                if (!isLikedLoaded && fragmentLikedVideos != null) {
                    Log.d("TabSwitch", "首次加载赞过数据");
                    fragmentLikedVideos.loadLikedVideos();
                    isLikedLoaded = true;
                } else if (fragmentLikedVideos != null) {
                    Log.d("TabSwitch", "赞过数据已加载，可选择性刷新");
                    // 可选：每次切换都刷新
                    // fragmentLikedVideos.loadLikedVideos();
                }
                break;
        }
    }
    /**
     * 检查并加载Tab数据
     */
    private void checkAndLoadTabData(int position) {
        switch (position) {
            case 0: // 作品页
                if (!isCompositionLoaded && !isRefreshing) {
                    Log.d("TabSwitch", "首次加载作品数据");
                    loadCompositionData();
                }
                break;

            case 1: // 赞过页
                if (!isLikedLoaded && !isRefreshing) {
                    Log.d("TabSwitch", "首次加载赞过数据");
                    loadLikedData();
                }
                break;
        }
    }
    /**
     * 加载当前Tab数据
     */
    private void loadCurrentTabData() {
        if (isRefreshing) {
            Log.d("FragmentSelfPage", "正在刷新中，跳过加载");
            return;
        }

        switch (currentTabPosition) {
            case 0:
                loadCompositionData();
                break;
            case 1:
                loadLikedData();
                break;
        }
    }

    /**
     * 加载作品数据
     */
    private void loadCompositionData() {
        if (fragmentComposition == null || isRefreshing) return;

        isRefreshing = true;
        Log.d("FragmentSelfPage", "开始加载作品数据");

        new Thread(() -> {
            try {
                // 模拟网络延迟
                Thread.sleep(100);

                requireActivity().runOnUiThread(() -> {
                    if (fragmentComposition != null && isAdded()) {
                        fragmentComposition.loadUserVideos();
                        isCompositionLoaded = true;
                        isRefreshing = false;
                        Log.d("FragmentSelfPage", "作品数据加载完成");
                    }
                });
            } catch (Exception e) {
                Log.e("FragmentSelfPage", "加载作品数据失败", e);
                isRefreshing = false;
            }
        }).start();
    }

    /**
     * 加载赞过数据
     */
    private void loadLikedData() {
        if (fragmentLikedVideos == null || isRefreshing) return;

        isRefreshing = true;
        Log.d("FragmentSelfPage", "开始加载赞过数据");

        new Thread(() -> {
            try {
                // 模拟网络延迟
                Thread.sleep(300);

                requireActivity().runOnUiThread(() -> {
                    if (fragmentLikedVideos != null && isAdded()) {
                        fragmentLikedVideos.loadLikedVideos();
                        isLikedLoaded = true;
                        isRefreshing = false;
                        Log.d("FragmentSelfPage", "赞过数据加载完成");
                    }
                });
            } catch (Exception e) {
                Log.e("FragmentSelfPage", "加载赞过数据失败", e);
                isRefreshing = false;
            }
        }).start();
    }

    /**
     * 刷新作品数据
     */
    private void refreshCompositionData() {
        if (isRefreshing) {
            Toast.makeText(requireContext(), "正在刷新，请稍候", Toast.LENGTH_SHORT).show();
            return;
        }

        isRefreshing = true;
        Log.d("FragmentSelfPage", "手动刷新作品数据");

        new Thread(() -> {
            try {
                Thread.sleep(500); // 模拟网络请求

                requireActivity().runOnUiThread(() -> {
                    if (fragmentComposition != null && isAdded()) {
                        fragmentComposition.loadUserVideos();
                        isCompositionLoaded = true;
                        isRefreshing = false;
                        Toast.makeText(requireContext(), "刷新成功", Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (Exception e) {
                Log.e("FragmentSelfPage", "刷新作品数据失败", e);
                isRefreshing = false;
                Toast.makeText(requireContext(), "刷新失败", Toast.LENGTH_SHORT).show();
            }
        }).start();
    }

    /**
     * 刷新赞过数据
     */
    /**
     * 刷新赞过数据
     */
    private void refreshLikedData() {
        if (isRefreshing) {
            Toast.makeText(requireContext(), "正在刷新，请稍候", Toast.LENGTH_SHORT).show();
            return;
        }

        isRefreshing = true;
        Log.d("FragmentSelfPage", "手动刷新赞过数据");

        new Thread(() -> {
            try {
                Thread.sleep(500); // 模拟网络请求

                requireActivity().runOnUiThread(() -> {
                    if (fragmentLikedVideos != null && isAdded()) {
                        // 使用新的刷新方法，确保强制重新加载
                        fragmentLikedVideos.refreshLikedVideos();
                        isLikedLoaded = true;
                        isRefreshing = false;
                        Toast.makeText(requireContext(), "刷新成功", Toast.LENGTH_SHORT).show();
                        Log.d("FragmentSelfPage", "赞过数据刷新完成");
                    }
                });
            } catch (Exception e) {
                Log.e("FragmentSelfPage", "刷新赞过数据失败", e);
                isRefreshing = false;
                Toast.makeText(requireContext(), "刷新失败", Toast.LENGTH_SHORT).show();
            }
        }).start();
    }

    /**
     * 设置初始Tab状态
     */
    private void setInitialTabState() {
        Log.d("TabSwitch", "设置初始Tab状态...");

        if (tabLayout_note_like_product.getTabCount() > 0) {
            TabLayout.Tab initialTab = tabLayout_note_like_product.getTabAt(0);
            if (initialTab != null) {
                // 选中第一个Tab
                initialTab.select();
                Log.d("TabSwitch", "初始Tab设置完成: 位置 0");

                // 确保初始状态正确
                currentTabPosition = 0;
                currentFragment = fragmentComposition;
            } else {
                Log.e("TabSwitch", "初始Tab为null");
            }
        } else {
            Log.e("TabSwitch", "TabLayout没有Tab");
        }
    }

    /**
     * 恢复到之前的Tab（错误恢复）
     */
    private void recoverPreviousTab() {
        Log.d("TabSwitch", "尝试恢复到之前的Tab: " + currentTabPosition);

        if (currentTabPosition >= 0 && currentTabPosition < tabLayout_note_like_product.getTabCount()) {
            TabLayout.Tab previousTab = tabLayout_note_like_product.getTabAt(currentTabPosition);
            if (previousTab != null) {
                previousTab.select();
                Log.d("TabSwitch", "已恢复到Tab: " + currentTabPosition);
            }
        }
    }

    /**
     * 调试Fragment状态
     */
    private void debugFragmentState(String tag) {
        Log.d("FragmentDebug", "=== " + tag + " ===");
        Log.d("FragmentDebug", "fragmentComposition: " + fragmentComposition);
        Log.d("FragmentDebug", "fragmentLikedVideos: " + fragmentLikedVideos);
        Log.d("FragmentDebug", "currentFragment: " + currentFragment);
        Log.d("FragmentDebug", "currentTabPosition: " + currentTabPosition);
        Log.d("FragmentDebug", "isCompositionLoaded: " + isCompositionLoaded);
        Log.d("FragmentDebug", "isLikedLoaded: " + isLikedLoaded);

        // 检查Fragment是否在Manager中
        Fragment compInManager = getChildFragmentManager().findFragmentByTag("composition");
        Fragment likedInManager = getChildFragmentManager().findFragmentByTag("liked");
        Log.d("FragmentDebug", "composition in Manager: " + compInManager);
        Log.d("FragmentDebug", "liked in Manager: " + likedInManager);

        // 检查TabLayout
        Log.d("FragmentDebug", "Tab count: " + tabLayout_note_like_product.getTabCount());
        Log.d("FragmentDebug", "Selected tab position: " + tabLayout_note_like_product.getSelectedTabPosition());
    }

    /**
     * 重置加载状态（用于用户登出等场景）
     */
    public void resetLoadStates() {
        isCompositionLoaded = false;
        isLikedLoaded = false;
    }
    private void displayUserAvatar(Context context, User user) {
        if (user == null) {
            imageButtonAvatar.setImageResource(R.drawable.user_avatar);
            return;
        }

        Log.d("Avatar", "显示用户头像，路径: " + user.getAvatarPath());

        Bitmap avatar = user.getAvatarBitmap(context);
        if (avatar != null) {
            imageButtonAvatar.setImageBitmap(avatar);
            Log.d("Avatar", "使用自定义头像");
        } else {
            imageButtonAvatar.setImageResource(R.drawable.user_avatar);
            Log.d("Avatar", "使用默认头像，可能原因: " +
                    (user.getAvatarPath() == null ? "头像路径为空" :
                            user.getAvatarPath().isEmpty() ? "头像路径为空字符串" :
                                    "文件不存在或加载失败"));
        }
    }

    private void showEditProfileDialog() {
        User currentUser = ActivityLogin.getCurrentUserFromSharedPrefrences(
                requireContext(),
                ((MainActivity) requireActivity()).getMySqLiteOpenHelper()
        );

        if (currentUser == null) {
            Toast.makeText(requireContext(), "用户未登录", Toast.LENGTH_SHORT).show();
            return;
        }

        String[] options = {"📷 编辑头像", "👤 编辑用户名", "🔑 重置密码"};

        new AlertDialog.Builder(requireContext())
                .setTitle("编辑资料")
                .setItems(options, (dialog, which) -> {
                    switch (which) {
                        case 0:
                            openAvatarSelection();
                            break;
                        case 1:
                            openUsernameEditDialog(currentUser);
                            break;
                        case 2:
                            openPasswordResetDialog(currentUser);
                            break;
                    }
                })
                .setNegativeButton("取消", (dialog, i) -> dialog.dismiss())
                .show();
    }

    private void openAvatarSelection() {
        debugPermissionStatus();

        // Android 13+ 尝试使用新的照片选择器（无需权限）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            openPhotoPicker();
        } else {
            // Android 12 及以下使用传统方式
            if (hasReadStoragePermission()) {
                pickImageFromGallery();
            } else {
                requestReadStoragePermission();
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
    private void openPhotoPicker() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_PICK_IMAGE);
            Log.d("PhotoPicker", "使用新的照片选择器");
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("PhotoPicker", "新的照片选择器不可用，回退到传统方式");
            // 如果新的选择器不可用，回退到传统方式
            if (hasReadStoragePermission()) {
                pickImageFromGallery();
            } else {
                requestReadStoragePermission();
            }
        }
    }

    private void pickImageFromGallery() {
        try {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            // 添加 FLAG_GRANT_READ_URI_PERMISSION
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            startActivityForResult(intent, REQUEST_PICK_IMAGE);
            Log.d("Gallery", "打开传统图库");
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), "无法打开图库", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean hasReadStoragePermission() {
        boolean hasPermission = ContextCompat.checkSelfPermission(requireContext(),
                Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        Log.d("Permission", "hasReadStoragePermission: " + hasPermission);
        return hasPermission;
    }

    private void requestReadStoragePermission() {
        Log.d("Permission", "请求存储权限");
        String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
        requestPermissions(permissions, REQUEST_PERMISSION_READ_STORAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        Log.d("Permission", "onRequestPermissionsResult: requestCode=" + requestCode);

        if (requestCode == REQUEST_PERMISSION_READ_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("Permission", "权限 granted，打开图库");
                // 权限 granted，打开图库
                pickImageFromGallery();
            } else {
                Log.d("Permission", "权限被拒绝");
                // 权限被拒绝
                handlePermissionDenied();
            }
        }
    }

    private void handlePermissionDenied() {
        boolean shouldShowRationale = shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE);
        Log.d("Permission", "shouldShowRequestPermissionRationale: " + shouldShowRationale);

        if (!shouldShowRationale) {
            // 用户选择了"不再询问"，需要引导用户去设置页面
            showGoToSettingsDialog();
        } else {
            // 用户只是简单拒绝，可以再次请求
            Toast.makeText(requireContext(), "需要存储权限才能选择头像", Toast.LENGTH_SHORT).show();
        }
    }

    private void showGoToSettingsDialog() {
        new AlertDialog.Builder(requireContext())
                .setTitle("权限被永久拒绝")
                .setMessage("您已永久拒绝存储权限。如需选择头像，请到应用设置中手动开启权限。")
                .setPositiveButton("去设置", (dialog, which) -> openAppSettings())
                .setNegativeButton("取消", null)
                .show();
    }

    private void openAppSettings() {
        try {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", requireContext().getPackageName(), null);
            intent.setData(uri);
            startActivity(intent);
            Log.d("Settings", "打开应用设置页面");
        } catch (Exception e) {
            e.printStackTrace();
            // 如果无法打开详细设置，尝试打开应用列表
            try {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
                startActivity(intent);
                Log.d("Settings", "打开应用列表设置");
            } catch (Exception ex) {
                ex.printStackTrace();
                Toast.makeText(requireContext(), "无法打开设置", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void debugPermissionStatus() {
        int permissionStatus = ContextCompat.checkSelfPermission(requireContext(),
                Manifest.permission.READ_EXTERNAL_STORAGE);

        Log.d("PermissionDebug", "当前权限状态: " + permissionStatus);
        Log.d("PermissionDebug", "PERMISSION_GRANTED: " + PackageManager.PERMISSION_GRANTED);

        boolean shouldShowRationale = shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE);
        Log.d("PermissionDebug", "shouldShowRequestPermissionRationale: " + shouldShowRationale);

        if (permissionStatus == PackageManager.PERMISSION_GRANTED) {
            Log.d("PermissionDebug", "权限已授予");
        } else {
            Log.d("PermissionDebug", "权限未授予");
            if (!shouldShowRationale) {
                Log.d("PermissionDebug", "用户选择了'不再询问'");
            }
        }

        Log.d("PermissionDebug", "Android版本: " + Build.VERSION.SDK_INT);
    }

    private void showEditIntroductionDialog() {
        User currentUser = ActivityLogin.getCurrentUserFromSharedPrefrences(
                requireContext(),
                ((MainActivity) requireActivity()).getMySqLiteOpenHelper()
        );

        if (currentUser == null) {
            Toast.makeText(requireContext(), "用户未登录", Toast.LENGTH_SHORT).show();
            return;
        }

        EditText editText = new EditText(requireContext());
        editText.setText(currentUser.getSelfIntroduction());
        editText.setSelection(editText.getText().length());
        editText.setSingleLine(false);
        editText.setMaxLines(5);
        editText.setPadding(60, 40, 60, 40);
        editText.setHint("请输入个人介绍，展示真实的你～");

        new AlertDialog.Builder(requireContext())
                .setTitle("编辑个人介绍")
                .setView(editText)
                .setPositiveButton("保存", (dialog, which) -> {
                    String newIntro = editText.getText().toString().trim();
                    if (newIntro.isEmpty()) {
                        Toast.makeText(requireContext(), "个人介绍不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    currentUser.setSelfIntroduction(newIntro);
                    try {
                        currentUser.updateSelfIntroduction(newIntro);
                        Toast.makeText(requireContext(), "保存成功", Toast.LENGTH_SHORT).show();
                        textViewSignatureContent.setText(newIntro);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(requireContext(), "保存失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    private void openUsernameEditDialog(User currentUser) {
        // 创建对话框内容布局
        LinearLayout layout = new LinearLayout(requireContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(60, 40, 60, 40);

        // 输入新用户名
        EditText inputNewUsername = new EditText(requireContext());
        inputNewUsername.setHint("请输入新用户名");
        inputNewUsername.setText(currentUser.getName());
        inputNewUsername.setSelection(inputNewUsername.getText().length()); // 光标置于末尾
        inputNewUsername.setSingleLine(true);

        // 输入当前密码（身份验证）
        EditText inputPassword = new EditText(requireContext());
        inputPassword.setHint("请输入当前密码");
        inputPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        inputPassword.setSingleLine(true);

        // 添加到布局
        layout.addView(inputNewUsername);
        layout.addView(inputPassword);

        // 构建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("修改用户名")
                .setView(layout);

        final AlertDialog dialog = builder.create();

        // 设置按钮（手动控制点击逻辑）
        dialog.setButton(AlertDialog.BUTTON_POSITIVE, "确认修改", (dialogInterface, i) -> {
            // 点击后不自动关闭
        });
        dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", (dialogInterface, i) -> {
            dialog.dismiss();
        });

        // 显示对话框
        dialog.show();

        // 获取"确认修改"按钮，设置自定义点击逻辑
        Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
        positiveButton.setOnClickListener(v -> {
            String newUsername = inputNewUsername.getText().toString().trim();
            String password = inputPassword.getText().toString();

            // 1. 校验当前密码是否正确
            if (!currentUser.getPassword().equals(password)) {
                Toast.makeText(requireContext(), "当前密码错误，请重新输入", Toast.LENGTH_SHORT).show();
                inputPassword.setText("");
                return;
            }

            // 2. 是否与当前用户名相同
            if (newUsername.equals(currentUser.getName())) {
                Toast.makeText(requireContext(), "新用户名与当前用户名相同，无需修改", Toast.LENGTH_SHORT).show();
                return;
            }

            // 3. 使用 ValidationUtils 专用方法校验用户名格式 ✅
            List<String> usernameErrors = ValidationUtils.validateUsername(newUsername);
            if (!usernameErrors.isEmpty()) {
                new AlertDialog.Builder(requireContext())
                        .setTitle("用户名不符合要求")
                        .setMessage(TextUtils.join("\n", usernameErrors))
                        .setPositiveButton("好的", null)
                        .show();
                return;
            }

            // 4. 检查新用户名是否已被其他用户占用
            User existingUser = ((MainActivity) requireActivity()).getMySqLiteOpenHelper().getUserByName(newUsername);
            if (existingUser != null && !existingUser.getId().equals(currentUser.getId())) {
                Toast.makeText(requireContext(), "该用户名已被其他用户使用", Toast.LENGTH_SHORT).show();
                inputNewUsername.setText("");
                return;
            }

            // ✅ 所有校验通过，执行保存逻辑
            saveNewUsername(currentUser, newUsername);

            // ✅ 更新 UI：使用正确的 TextView ID
            textViewUsername.setText(newUsername); // ✅ 正确的 ID

            // 提示成功
            Toast.makeText(requireContext(), "用户名已修改为: " + newUsername, Toast.LENGTH_SHORT).show();

            // 关闭对话框
            dialog.dismiss();
        });
    }

    private void saveNewUsername(User currentUser, String newUsername) {
        if (newUsername.equals(currentUser.getName())) {
            Toast.makeText(requireContext(), "新用户名与当前用户名相同", Toast.LENGTH_SHORT).show();
            return;
        }

        User existingUser = ((MainActivity) requireActivity()).getMySqLiteOpenHelper().getUserByName(newUsername);
        if (existingUser != null) {
            Toast.makeText(requireContext(), "该用户名已存在，请使用其他用户名", Toast.LENGTH_LONG).show();
            return;
        }

        try {
            currentUser.setName(newUsername);
            currentUser.save();
            ActivityLogin.saveCurrentUserToSharedPreferences(requireContext(), currentUser);
            updateUsernameInUI(newUsername);

            // 通知主页刷新
            if (requireActivity() instanceof MainActivity) {
                ((MainActivity) requireActivity()).refreshHomePage();
            }

            Toast.makeText(requireContext(), "用户名修改成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), "用户名修改失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void updateUsernameInUI(String newUsername) {
        TextView textViewUsername = getView().findViewById(R.id.textView23);
        if (textViewUsername != null) {
            textViewUsername.setText(newUsername);
        }
    }

    private void openPasswordResetDialog(User currentUser) {
        // 创建对话框内容布局
        LinearLayout layout = new LinearLayout(requireContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(60, 40, 60, 40);

        // 输入原密码
        EditText inputOldPassword = new EditText(requireContext());
        inputOldPassword.setHint("请输入原密码");
        inputOldPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        inputOldPassword.setSingleLine(true);

        // 输入新密码
        EditText inputNewPassword = new EditText(requireContext());
        inputNewPassword.setHint("请输入新密码");
        inputNewPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        inputNewPassword.setSingleLine(true);

        // 添加到布局
        layout.addView(inputOldPassword);
        layout.addView(inputNewPassword);

        // 构建对话框（先不显示）
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("修改密码")
                .setView(layout);

        final AlertDialog dialog = builder.create();

        // 设置按钮（但不自动关闭）
        dialog.setButton(AlertDialog.BUTTON_POSITIVE, "确认修改", (dialogInterface, i) -> {
            // 点击后不自动关闭，由我们手动控制
        });
        dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", (dialogInterface, i) -> {
            dialog.dismiss();
        });

        // 显示对话框
        dialog.show();

        // 获取"确认修改"按钮，设置自定义点击逻辑
        Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
        positiveButton.setOnClickListener(v -> {
            String oldPassword = inputOldPassword.getText().toString();
            String newPassword = inputNewPassword.getText().toString().trim();

            // 1. 校验原密码是否正确
            if (!currentUser.getPassword().equals(oldPassword)) {
                Toast.makeText(requireContext(), "原密码错误，请重新输入", Toast.LENGTH_SHORT).show();
                inputOldPassword.setText(""); // 清空便于重输
                return;
            }

            // 2. 新密码不能与原密码相同
            if (newPassword.equals(oldPassword)) {
                Toast.makeText(requireContext(), "新密码不能与原密码相同", Toast.LENGTH_SHORT).show();
                inputNewPassword.setText("");
                return;
            }

            // 3. 使用 ValidationUtils 校验新密码复杂度
            List<String> passwordErrors = ValidationUtils.validatePassword(newPassword, currentUser.getName());
            if (!passwordErrors.isEmpty()) {
                new AlertDialog.Builder(requireContext())
                        .setTitle("密码不符合安全要求")
                        .setMessage(TextUtils.join("\n", passwordErrors))
                        .setPositiveButton("好的", null)
                        .show();
                return;
            }

            // ✅ 所有校验通过，执行保存逻辑
            saveNewPassword(currentUser, newPassword);

            // 提示成功
            Toast.makeText(requireContext(), "密码修改成功", Toast.LENGTH_SHORT).show();

            // 关闭对话框
            dialog.dismiss();
        });
    }

    private void saveNewPassword(User currentUser, String newPassword) {
        try {
            currentUser.setPassword(newPassword);
            currentUser.save();
            ActivityLogin.saveCurrentUserToSharedPreferences(requireContext(), currentUser);
            Toast.makeText(requireContext(), "密码修改成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), "密码修改失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == getActivity().RESULT_OK && data != null) {
            if (requestCode == REQUEST_PICK_IMAGE) {
                try {
                    Uri imageUri = data.getData();
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(requireContext().getContentResolver(), imageUri);

                    imageButtonAvatar.setImageBitmap(bitmap);

                    User currentUser = ActivityLogin.getCurrentUserFromSharedPrefrences(
                            requireContext(),
                            ((MainActivity) requireActivity()).getMySqLiteOpenHelper()
                    );
                    if (currentUser != null) {
                        boolean success = currentUser.saveAvatarBitmap(requireContext(), bitmap);
                        if (success) {
                            Toast.makeText(requireContext(), "头像更新成功", Toast.LENGTH_SHORT).show();
                            // 通知主页刷新
                            if (requireActivity() instanceof MainActivity) {
                                ((MainActivity) requireActivity()).refreshHomePage();
                            }
                        } else {
                            Toast.makeText(requireContext(), "头像保存失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(requireContext(), "用户未登录", Toast.LENGTH_SHORT).show();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(requireContext(), "加载图片失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }

    /**
     * 刷新作品和点赞视频页面
     * 供MainActivity调用，确保评论后数据同步
     */
    /**
     * 刷新作品和点赞视频页面
     * 供MainActivity调用，确保评论后数据同步
     */
    public void refreshCompositionAndLikedVideos() {
        Log.d("FragmentSelfPage", "刷新作品和点赞视频页面");

        // 刷新当前显示的Fragment
        if (currentFragment instanceof FragmentComposition) {
            // 如果当前显示的是作品页面
            ((FragmentComposition) currentFragment).loadUserVideos();
            Log.d("FragmentSelfPage", "刷新作品页面");
        } else if (currentFragment instanceof FragmentLikedVideos) {
            // 如果当前显示的是点赞视频页面
            ((FragmentLikedVideos) currentFragment).refresh();
            Log.d("FragmentSelfPage", "刷新点赞视频页面");
        } else {
            // 如果当前Fragment未知，尝试刷新两个页面
            if (fragmentComposition != null) {
                fragmentComposition.loadUserVideos();
                Log.d("FragmentSelfPage", "刷新作品页面（备用）");
            }
            if (fragmentLikedVideos != null) {
                fragmentLikedVideos.refresh();
                Log.d("FragmentSelfPage", "刷新点赞视频页面（备用）");
            }
        }
        // 刷新用户获赞数
        User currentUser = ActivityLogin.getCurrentUserFromSharedPrefrences(
                requireContext(),
                ((MainActivity) requireActivity()).getMySqLiteOpenHelper()
        );
        if (currentUser != null) {
            refreshUserLikesCount(currentUser.getId());
        }
    }
    // 在 FragmentComposition 类中添加这些方法
// 在 FragmentComposition 类中添加这些方法

    /**
     * 显示作品操作对话框（删除/编辑）
     */

}